package com.dlc.shop.delivery.multishop.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.enums.DvyType;
import com.dlc.shop.bean.enums.OrderActivityType;
import com.dlc.shop.bean.model.Order;
import com.dlc.shop.bean.model.OrderItem;
import com.dlc.shop.bean.model.PlatformAddr;
import com.dlc.shop.bean.model.UserAddrOrder;
import com.dlc.shop.common.exception.YamiShopBindException;
import com.dlc.shop.common.response.ServerResponseEntity;
import com.dlc.shop.common.util.Arith;
import com.dlc.shop.common.util.BeanUtil;
import com.dlc.shop.delivery.common.model.ChinaDeliveryOrder;
import com.dlc.shop.delivery.common.model.DeliveryOrder;
import com.dlc.shop.delivery.common.model.OrderSelfStation;
import com.dlc.shop.delivery.common.param.DeliveryOrderItemParam;
import com.dlc.shop.delivery.common.param.DvyOrderParam;
import com.dlc.shop.delivery.common.param.OrderParam;
import com.dlc.shop.delivery.common.service.ChinaDeliveryOrderService;
import com.dlc.shop.delivery.common.service.OrderSelfStationService;
import com.dlc.shop.security.multishop.util.SecurityUtils;
import com.dlc.shop.service.OrderItemService;
import com.dlc.shop.service.OrderService;
import com.dlc.shop.service.PlatformAddrService;
import com.dlc.shop.service.UserAddrOrderService;
import com.dlc.shop.delivery.common.service.ChinaDeliveryOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 国内物流发货-订单物流
 * @author liyong
 */
@RestController
@RequestMapping("/order/delivery/chinaDeliveryOrder")
@Tag(name = "国内物流发货-订单物流")
@AllArgsConstructor
public class ChinaDeliveryOrderController {

    private final ChinaDeliveryOrderService chinaDeliveryOrderService;

    private final UserAddrOrderService userAddrOrderService;

    private final OrderService orderService;

    private final OrderItemService orderItemService;

    private final OrderSelfStationService orderSelfStationService;

    private final PlatformAddrService platformAddrService;


    /**
     * 订单项待发货数量查询
     */
    @GetMapping("/getOrderItemUnDelivery/{orderNumber}")
    @Operation(summary = "订单项待发货数量查询")
    @Parameter(name = "orderNumber", description = "订单号" )
    public ServerResponseEntity<Order> getOrderItemUnDelivery(@PathVariable("orderNumber") String orderNumber) {

        Long shopId = orderService.getOrderAndOrderItemByOrderNumber(orderNumber).getShopId();

        Order order = orderService.getOrderByOrderNumberAndShopId(orderNumber, shopId, true);
        if (Objects.isNull(order)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        //用户地址
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        List<PlatformAddr> list = platformAddrService.queryList();
        order.setPlatformAddrs(list);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber,false);
        if (CollectionUtils.isEmpty(orderItems)) {
            // 订单不存在
            throw new YamiShopBindException("yami.order.no.exist");
        }
        Map<Long, Integer> orderItemMap = null;
        if (Objects.nonNull(order.getRefundStatus())) {
            orderItemMap = orderService.getOrderItemMap(order.getOrderId());
        }
        // 获取组合map
        Map<Long, List<OrderItem>> comboMap = orderItems.stream().filter(item -> Objects.equals(item.getActivityType(), OrderActivityType.COMBO_PROD.value()))
                .collect(Collectors.groupingBy(OrderItem::getActivityId));
        //查询已发货数量
        for (OrderItem orderItem : orderItems) {
            //根据状态查询可发货数量
            orderItem.setChangeNum(orderItem.getStatus() == -1 ? orderItem.getProdCount() : orderItem.getStatus());
            orderItem.setProdCount(orderItem.getChangeNum());
            if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(orderItem.getOrderItemId()))) {
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getOrderItemId()));
            } else if (Objects.nonNull(orderItemMap) && Objects.nonNull(orderItemMap.get(0L))) {
                orderItem.setReturnMoneySts(orderItemMap.get(0L));
            }
            // 退款修改赠品状态
            if(Objects.nonNull(orderItemMap) && Objects.equals(orderItem.getActivityType(),OrderActivityType.GIVEAWAY.value()) && orderItemMap.containsKey(orderItem.getActivityId())){
                orderItem.setReturnMoneySts(orderItemMap.get(orderItem.getActivityId()));
            }
            if(comboMap.containsKey(orderItem.getOrderItemId())){
                comboMap.get(orderItem.getOrderItemId()).forEach(orderItemVO -> orderItemVO.setReturnMoneySts(orderItem.getReturnMoneySts()));
            }
        }
        order.setOrderItems(orderItems);
        return ServerResponseEntity.success(order);
    }


    @PutMapping("/orderItemsDelivery")
    @Operation(summary = "订单项国内分包裹发货")
    public ServerResponseEntity<Void> orderItemsDelivery(@RequestBody DeliveryOrderItemParam deliveryOrderParam) {
        //Long shopId = SecurityUtils.getShopUser().getShopId();
        Long shopId = deliveryOrderParam.getSelectOrderItems().get(0).getShopId();
        chinaDeliveryOrderService.saveDeliveriesInfo(deliveryOrderParam, shopId);
        return ServerResponseEntity.success();
    }

    @PutMapping("/getOrderDeliveries/{orderNumber}")
    @Operation(summary = "根据订单号查询订单物流包裹信息")
    @Parameter(name = "orderNumber", description = "订单号" )
    public ServerResponseEntity<List<ChinaDeliveryOrder>> getOrderDeliveries(@PathVariable("orderNumber") String orderNumber) {
        List<ChinaDeliveryOrder> deliveryOrders = chinaDeliveryOrderService.listDetailDelivery(orderNumber);
        return ServerResponseEntity.success(deliveryOrders);
    }

    @PutMapping("/updateOrderDeliveries")
    @Operation(summary = "修改订单物流包裹信息")
    public ServerResponseEntity<Void> updateOrderDeliveries(@RequestBody DvyOrderParam dvyOrderParam) {
        List<DeliveryOrder> deliveryOrders = dvyOrderParam.getDeliveryOrders();
        chinaDeliveryOrderService.updateOrderDeliveries(deliveryOrders);
        return ServerResponseEntity.success();
    }


    @GetMapping("/orderInfo/{orderNumber}")
    @Operation(summary = "根据订单号获取订单物流包裹信息")
    @Parameter(name = "orderNumber", description = "订单号" )
    public ServerResponseEntity<OrderParam> info(@PathVariable("orderNumber") String orderNumber) {
        Long shopId = SecurityUtils.getShopUser().getShopId();
        Order order = orderService.getOrderDetailByOrderNumberAndShopId(orderNumber, shopId);
        orderItemService.handleActivityOrderItem(order.getOrderItems(),null);
        // 处理下赠品
        for (OrderItem orderItem : order.getOrderItems()) {
            orderItem.setPlatformShareReduce(Objects.isNull(orderItem.getPlatformShareReduce()) ? 0.0 : orderItem.getPlatformShareReduce());
            orderItem.setShareReduce(Objects.isNull(orderItem.getShareReduce()) ? 0.0 : orderItem.getShareReduce());
            orderItem.setShopShareReduce(Arith.sub(orderItem.getShareReduce(),orderItem.getPlatformShareReduce()));
        }

        if (Objects.nonNull(order.getDvyType()) && order.getDvyType().equals(DvyType.STATION.value())) {
            OrderSelfStation orderSelfStation = orderSelfStationService.getOne(new LambdaQueryWrapper<OrderSelfStation>().eq(OrderSelfStation::getOrderNumber, order.getOrderNumber()));
            order.getUserAddrOrder().setMobile(orderSelfStation.getStationUserMobile());
            order.getUserAddrOrder().setReceiver(orderSelfStation.getStationUserName());
        }
        OrderParam orderParam = BeanUtil.map(order, OrderParam.class);
        orderParam.setFreeFreightAmount(order.getFreeTransfee());
        orderParam.setScore(orderParam.getOrderItems().stream().mapToLong(OrderItem::getUseScore).sum());
        //查询包裹信息
        List<ChinaDeliveryOrder> deliveryOrders = chinaDeliveryOrderService.getAndDeliveryItemInfo(orderNumber);
        orderParam.setChinaDeliveryExpresses(deliveryOrders);
        return ServerResponseEntity.success(orderParam);
    }

   @GetMapping("/deliveryOrder/{orderDeliveryId}")
   @Operation(summary = "物流包裹查询接口" , description = "根据orderDeliveryId查询订单包裹信息")
   @Parameter(name = "orderDeliveryId", description = "订单物流包裹id" )
   public ServerResponseEntity<ChinaDeliveryOrder> info(@PathVariable("orderDeliveryId") Long orderDeliveryId) {
       ChinaDeliveryOrder deliveryOrder = chinaDeliveryOrderService.deliveryOrderItemInfo(orderDeliveryId);
       return ServerResponseEntity.success(deliveryOrder);
   }

}
